﻿using System;
using System.Web.Mvc;
using SlamCms.Configuration;
using SlamCms.Data;
using SlamCms.Data.Repositories;
using SlamCms.SharePointServices;
using SlamCms.Web;

namespace SlamCms.Areas._admin.Controllers
{
	public class ContentManagementController : AdminBaseController
	{
		private readonly IContentItemRepository contentItemRepository;
		private readonly SlamCmsContext slamCmsContext;

		public ContentManagementController(IContentItemRepository contentItemRepository, SlamCmsContext slamCmsContext)
		{
			this.contentItemRepository = contentItemRepository;
			this.slamCmsContext = slamCmsContext;
		}

		[HttpGet]
		public ActionResult Verify(string contentItemId)
		{
            if (!slamCmsContext.User.IsContentExpirationAdmin())
                return this.NotAuthorized();

			var contentItem = slamCmsContext.CreateQuery(QueryBuilderOptions.AllZones)
											.FilterContentItemId(contentItemId)
											.GetFirstOrDefault();

			if (contentItem == null)
				return this.NotFound();

			if (!slamCmsContext.User.CanEdit(contentItem))
				return this.NotAuthorized();

			var userId = slamCmsContext.User.UserId;

			var daysToExtend = contentItem.ContentType.ExpirationPeriod ?? ConfigurationHelpers.GetEnvironmentSetting(Constants.Settings.ContentExpirationPeriod, 30);

			// TODO Log Warning when the content type expiration period is null and the user is trying to extend the expiration date

			var expirationDate = DateTime.Now.Date.AddDays(daysToExtend);
			contentItemRepository.UpdateExpirationDate(contentItemId, expirationDate, userId);

			slamCmsContext.Data.Cache.InvalidateQueries();

			return Redirect(ConfigurationManager.Environment.DefaultApplication.AdminUrl);
		}

		[HttpGet]
		public ActionResult Retire(string contentItemId)
		{
            if (!slamCmsContext.User.IsContentExpirationAdmin())
                return this.NotAuthorized();

			var contentItem = slamCmsContext.CreateQuery(QueryBuilderOptions.AllZones)
											.FilterContentItemId(contentItemId)
											.GetFirstOrDefault();

			if (contentItem == null)
				return this.NotFound();

			if (!slamCmsContext.User.CanDelete(contentItem))
				return this.NotAuthorized();

			DocumentLibraryService.UpdateItemModerationStatus(contentItem.GetLibraryUrl(), contentItem.ListId, contentItem.ListRelativeId, ModerationStatus.Denied);

			slamCmsContext.Data.Cache.InvalidateQueries();

			return Redirect(ConfigurationManager.Environment.DefaultApplication.AdminUrl);
		}
	}
}
